package transformFactory;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class OperateImage {
	/**
	 * 长高等比例缩小图片
	 * 
	 * @param srcImagePath
	 *            读取图片路径
	 * @param toImagePath
	 *            写入图片路径
	 * @param ratio
	 *            缩小比例
	 * @throws IOException
	 */
	public void reduceImageEqualProportion(String srcImagePath,
			String toImagePath, int ratio) throws IOException {
		FileOutputStream out = null;
		try {
			// System.out.println("srcImagePath:"+srcImagePath+"-"+"toImagePath:"+toImagePath);
			// 读入文件
			File file = new File(srcImagePath);
			// 构造Image对象
			BufferedImage src = javax.imageio.ImageIO.read(file);
			int width = src.getWidth();
			int height = src.getHeight();

			if (width > 830) {
				// System.out.println("width:"+width+"height:"+height);
				// 通过原始图片大小对其处以830再向上取整得到缩小的比率
				ratio = (int) Math.ceil((float) width / 830);
				// System.out.println("ratio:"+ratio);
				// 缩小边长
				BufferedImage tag = new BufferedImage(width / ratio, height
						/ ratio, BufferedImage.TYPE_INT_RGB);
				// 绘制缩小后的图片
				tag.getGraphics().drawImage(src, 0, 0, width / ratio,
						height / ratio, null);
				out = new FileOutputStream(toImagePath);
				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
				encoder.encode(tag);
				System.out.println("tag.getWidth():" + tag.getWidth());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
